#include <stdio.h>
#include <math.h>
#include <gmp.h>
#include <time.h>




FILE *arq;

int main()
{
    mpf_t a1,a2,b1,b2,t1,t2,p1,p2,pi;
    clock_t begin, end;
    int n;

    arq = fopen("pi.txt","w+");

    mpf_set_default_prec (40000000);

    begin= clock();
    mpf_init(a1);mpf_init(a2);
    mpf_init(b1);mpf_init(b2);
    mpf_init(t1);mpf_init(t2);
    mpf_init(p1);mpf_init(p2);
    mpf_init(pi);


    mpf_set_d ( a2, 1);
    mpf_set_d ( b2, 0);
    mpf_set_d ( t2, 0.25);
    mpf_set_d ( p2, 1);

    mpf_sqrt_ui(b2,2);
    mpf_ui_div(b2,1,b2);

    for(n=0;n<22;n++){

        mpf_set (a1,a2);
        mpf_set (b1,b2);
        mpf_set (t1,t2);
        mpf_set (p1,p2);


        //a2=( a1+b1 ) / 2;
        mpf_add(a2,a1,b1);
        mpf_div_ui(a2,a2,2);

        //b2=sqrt( (a1*b1));
        mpf_mul(b2,b1,a1);
        mpf_sqrt(b2,b2);

        //t2=(t1)- (p2 * pow(((a1)-(a2)),2));
        mpf_sub(t2,a1,a2);
        mpf_pow_ui(t2,t2,2);
        mpf_mul(t2,t2,p1);
        mpf_sub(t2,t1,t2);

        //p2= 2*(p1);
        mpf_mul_ui(p2,p1,2);

        /*printf("\nIteracao %d\n", n);
        gmp_printf ("a = %.*Ff \n", 50,a2);
        gmp_printf ("b = %.*Ff \n", 50,b2);
        gmp_printf ("t = %.*Ff \n", 50,t2);
        gmp_printf ("p = %.*Ff \n", 2,p2);
        */

    }

    //pi=(pow((a[n]+b[n]),2)) / (4*t[n]);

    mpf_add(pi,a2,b2);
    mpf_pow_ui(pi,pi,2);
    mpf_mul_ui(t1,t2,4);
    mpf_div(pi,pi,t1);

    if(arq != NULL)
      mpf_out_str (arq,10,0, pi);
    end = clock();

    printf("\nTempo do calculo: %lf segundos\n",(double)((end - begin)/CLOCKS_PER_SEC));


    fclose(arq);
    return 0;
}
